<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table :data="this.userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="modifyUser(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteFrom(scope.row.id)"
            ></el-button>
            <!-- 其他功能按钮 -->
            <el-tooltip :enterable="false" content="分配角色" placement="top">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-share"
                @click="allocating(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size.sync="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户提示框 -->
    <el-dialog title="提示" :visible.sync="addDialogVisible" width="50%" @close="addCloseFrom">
      <el-form :model="addForm" :rules="addRules" label-width="70px" ref="addFromRef">
        <!-- prop是绑定的用户添加列表的数据的验证规则 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户提示框 -->
    <el-dialog title="修改用户信息" :visible.sync="modifyFormVisible" @close="modifyCloseFrom">
      <el-form :model="modifyFrom">
        <el-form-item label="用户名" label-width="90px">
          <el-input v-model="modifyFrom.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form :model="modifyFrom" :rules="modifyRules" ref="modifyFormRef" label-width="100px">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="modifyFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="modifyFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyValidate">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色提示框 -->
    <el-dialog title="分配角色" :visible.sync="allocatingFormVisible">
      <el-form ref="form" :model="allocatinginfo" label-width="100px">
        <el-form-item label="当前的用户">
          <el-input v-model="allocatinginfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前的角色">
          <el-input v-model="allocatinginfo.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配新角色">
          <el-select v-model="allocatingLisRegion" placeholder="请选择">
            <el-option
              v-for="item in allocatingList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="allocatingFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAllocatingForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
    // 验证手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法手机号"));
    };
    return {
      // 获取用户列表参数
      queryInfo: {
        query: "",
        // 当前显示的页数
        pagenum: 1,
        // 当前显示的每页条数
        pagesize: 5
      },
      // 用户列表数据
      userlist: [],
      // 总数据条数
      total: 0,
      addDialogVisible: false,
      // 用户添加的数据列表
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 用户列表的验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 5 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 修改用户提示框的显示与隐藏
      modifyFormVisible: false,
      // 修改用户信息的数据
      modifyFrom: {
        username: "",
        email: "",
        mobile: ""
      },
      // 修改用户的验证规则
      modifyRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 分配角色对话框是否显示
      allocatingFormVisible: false,
      // 分配角色的数据列表
      allocatinginfo: {},
      allocatingList: [],
      allocatingLisRegion: ""
    };
  },
  methods: {
    async getUserList() {
      // 发送axios获取用户列表数据
      // get传递参数用params
      const { data } = await this.$http.get("users", {
        params: this.queryInfo
      });
      // console.log(data);
      if (data.meta.status != 200)
        return this.$message.error("获取管理员列表失败");
      this.userlist = data.data.users;
      this.total = data.data.total;
      // console.log(this.queryInfo);
      // console.log(this.userlist);

      // console.log(this.userlist);
    },
    // 每条页数发生改变时触发的函数
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 当前页发生改变时触发的函数
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async userStateChanged(userinfo) {
      const { data } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (data.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("状态更新失败");
      }
      this.$message.success(data.meta.msg);
    },
    addCloseFrom() {
      // 因为要添加重置事件 需要获取到表单的所有内容 所以要加上ref属性
      this.$refs.addFromRef.resetFields();
    },
    addUsers() {
      this.$refs.addFromRef.validate(async validat => {
        if (!validat) return;
        //发送请求添加用户
        const { data } = await this.$http.post("users", this.addForm);
        console.log(data);
        if (data.meta.status !== 201)
          return this.$message.error("用户添加失败");
        this.$message.success(data.meta.msg);
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    // 修改按钮的内容
    async modifyUser(id) {
      this.modifyFormVisible = true;
      // console.log(id);
      // 发送请求显示数据
      const { data } = await this.$http.get("users/" + id);
      // console.log(data);
      if (data.meta.status != 200) {
        return this.$message.error(data.meta.msg);
      }
      this.modifyFrom = data.data;
      this.$message.success(data.meta.msg);
    },
    // 关闭修改对话框
    modifyCloseFrom() {
      this.$refs.modifyFormRef.resetFields();
    },
    // 修改对话框的预校验
    modifyValidate() {
      this.$refs.modifyFormRef.validate(async validat => {
        // console.log(validat);
        if (!validat) return;
        // 发送请求修改用户接口
        const { data } = await this.$http.put("users/" + this.modifyFrom.id, {
          email: this.modifyFrom.email,
          mobile: this.modifyFrom.mobile
        });
        // console.log(data);
        if (data.meta.status != 200) return this.$message.error(data.meta.msg);

        this.modifyFormVisible = false;
        this.getUserList();
        this.$message.success(data.meta.msg);
        console.log(this.modifyFrom);
      });
    },
    // 删除用户数据
    async deleteFrom(id) {
      const confirm = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirm !== "confirm") return this.$message.info(data.meta.msg);
      // 调用删除接口
      const { data } = await this.$http.delete("users/" + id);
      // console.log(data);
      if (data.meta.status != 200) return this.$message.error(data.meta.msg);
      this.getUserList();
      this.queryInfo.pagenum = 1;
      this.$message.success(data.meta.msg);
    },
    // 分配角色
    async allocating(role) {
      this.allocatinginfo = role;
      const { data } = await this.$http.get("roles");
      this.allocatingList = data.data;
      this.allocatingFormVisible = true;
    },
    // 分配角色成功
    async addAllocatingForm() {
if(!this.allocatingLisRegion) return this.$message.error('更新失败')     
      const { data } = await this.$http.put(`users/${this.allocatinginfo.id}/role`,{rid:this.allocatingLisRegion});
      // console.log(data);
      if(data.meta.status!=200)return this.$message.error(data.meta.msg)
      this.$message.success(data.meta.msg)
      this.getUserList()
      this.allocatingFormVisible=false
    }
  }
};
</script>

<style lang="less" scoped>
</style>
